<template>
  <div class="detail-modal" role="dialog" aria-modal="true">
    <div class="detail-layout">
      <!-- 左侧媒体展示区 -->
      <div class="media-pane" :style="bgStyle" v-if="images.length > 0">
        <img v-if="images.length" :src="images[currentIndex]" alt="动态图片" class="media" />
        <div v-else class="media-empty">暂无图片</div>
        <button v-if="images.length > 1" class="chevron chevron-left" @click="prevImage" aria-label="上一张">‹</button>
        <button v-if="images.length > 1" class="chevron chevron-right" @click="nextImage" aria-label="下一张">›</button>
      </div>

      <!-- 右侧信息交互区 -->
      <div class="info-pane" :class="{ 'full-width': images.length === 0 }">
        <div class="info-header">
          <div class="avatar">
            <img v-if="post?.avatar_url" :src="post.avatar_url" alt="头像" />
            <span v-else>{{ (post?.username || 'U').slice(0,1).toUpperCase() }}</span>
          </div>
          <div class="user-meta">
            <div class="nickname">{{ post?.username || '用户' }}</div>
            <div class="meta-row">
              <span class="time">{{ formatTime(post?.created_at) }}</span>
              <span v-if="post?.city && post.city !== '未设置'" class="city">📍 {{ post.city }}</span>
            </div>
          </div>
        </div>
        <div class="content-fixed">
          <div class="content-text">{{ post?.content }}</div>
          <div v-if="post?.tags?.length" class="tags">
            <span v-for="t in post.tags" :key="t" class="tag">#{{ t }}</span>
          </div>
        </div>

        <div class="comments-scroll">
          <div class="comments">
            <div class="comments-title">评论</div>
            <div v-if="commentsLoading" class="comments-loading">加载评论...</div>
            <div v-else class="comment-list">
              <div v-for="c in comments" :key="c.comment_id" class="comment-item">
                <div class="comment-author">{{ c.username }}</div>
                <div class="comment-content">{{ c.content }}</div>
                <div class="comment-time">{{ formatTime(c.created_at) }}</div>
              </div>
            </div>
          </div>
        </div>

        <div class="info-footer">
          <input
            v-model="newComment"
            type="text"
            class="comment-input"
            placeholder="写下你的想法..."
            @keydown.enter="submitComment"
          />
          <button class="send-btn" :disabled="!newComment.trim()" @click="submitComment">发送</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, computed } from 'vue'
import { getPostDetail, getComments, createComment } from '@/api/community'

const props = defineProps<{ postId: number }>()
const emit = defineEmits<{ (e: 'close'): void }>()

const post = ref<any>(null)
const images = ref<string[]>([])
const currentIndex = ref(0)
const comments = ref<any[]>([])
const commentsLoading = ref(false)
const newComment = ref('')
const bodyRef = ref<HTMLElement | null>(null)

const emitClose = () => emit('close')

const bgStyle = computed(() => {
  const src = images.value[currentIndex.value]
  return src
    ? { backgroundImage: `url(${src})` }
    : { backgroundColor: '#000' }
})

const formatTime = (t?: string) => {
  if (!t) return ''
  const d = new Date(t)
  return d.toLocaleString('zh-CN', { hour12: false })
}

const loadDetail = async () => {
  const resp: any = await getPostDetail(props.postId)
  post.value = resp?.data?.data || resp?.data || resp
  const imgs = post.value?.image_urls || []
  images.value = Array.isArray(imgs) ? imgs : (post.value?.image ? [post.value.image] : [])
  currentIndex.value = 0
}

const loadComments = async () => {
  commentsLoading.value = true
  try {
    const resp: any = await getComments(props.postId)
    const list = resp?.data?.data?.comments || resp?.data?.comments || resp?.comments || []
    comments.value = Array.isArray(list) ? list : []
  } finally { commentsLoading.value = false }
}

const submitComment = async () => {
  const text = newComment.value.trim()
  if (!text) return
  await createComment(props.postId, { content: text })
  newComment.value = ''
  loadComments()
}

const prevImage = () => {
  currentIndex.value = (currentIndex.value - 1 + images.value.length) % images.value.length
}
const nextImage = () => {
  currentIndex.value = (currentIndex.value + 1) % images.value.length
}

const onKeydown = (e: KeyboardEvent) => {
  if (e.key === 'Escape') emitClose()
  else if (e.key === 'ArrowLeft' && images.value.length) prevImage()
  else if (e.key === 'ArrowRight' && images.value.length) nextImage()
}

onMounted(() => {
  loadDetail()
  loadComments()
  window.addEventListener('keydown', onKeydown)
})
onUnmounted(() => {
  window.removeEventListener('keydown', onKeydown)
})
</script>

<style scoped>
.detail-modal {
  width: min(1200px, 80vw);
  height: 85vh;
  background: #111;
  border-radius: 12px;
  box-shadow: 0 20px 50px rgba(0,0,0,0.3);
  transform: scale(1);
  animation: appear 0.18s ease-out;
}

@keyframes appear { from { transform: scale(0.95); opacity: 0 } to { transform: scale(1); opacity: 1 } }

.detail-layout {
  display: flex;
  height: 100%;
}

.media-pane {
  flex: 1 1 0;
  background-color: #000;
  background-size: cover;
  background-position: center;
  filter: none;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.media-pane::before {
  content: '';
  position: absolute;
  inset: 0;
  background: inherit;
  filter: blur(18px) brightness(0.7);
}

.media {
  position: relative;
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  z-index: 1;
}

.media-empty { color: #888; z-index: 1; }

.chevron {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  width: 56px;
  height: 56px;
  border-radius: 50%;
  border: none;
  background: rgba(255,255,255,0.15);
  color: #fff;
  font-size: 36px;
  cursor: pointer;
  z-index: 2;
  transition: background 0.2s, opacity 0.2s;
  opacity: 0.5;
}
.chevron:hover { background: rgba(255,255,255,0.3); opacity: 1 }
.chevron-left { left: 16px }
.chevron-right { right: 16px }

.info-pane { width: 400px; background: #fff; display: flex; flex-direction: column; }
.info-pane.full-width { width: 100%; max-width: 800px; margin: 0 auto; }

.info-header {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  border-bottom: 1px solid #eee;
  position: relative;
}
.detail-modal { position: relative; }
.avatar { width: 40px; height: 40px; border-radius: 50%; overflow: hidden; background: #e8f5e9; display:flex; align-items:center; justify-content:center; color:#4CAF50; font-weight:700 }
.avatar img { width: 100%; height: 100%; object-fit: cover }
.user-meta { flex: 1 1 auto }
.nickname { font-size: 15px; font-weight: 600; color: #222 }
.meta-row { font-size: 12px; color: #888; display: flex; gap: 10px }
.ghost-follow { border: 1px solid #ddd; background: transparent; color: #333; border-radius: 999px; padding: 6px 12px; cursor: pointer; transition: border-color 0.2s, color 0.2s }
.ghost-follow:hover { border-color: #4CAF50; color: #4CAF50 }

.content-fixed { flex: 0 0 auto; padding: 20px 16px; border-bottom: 1px solid #eee; }
.comments-scroll { flex: 1 1 auto; overflow-y: auto; padding: 16px; }
.content-text { font-size: 16px; line-height: 1.7; color: #333; white-space: pre-wrap }
.tags { margin-top: 12px }
.tag { display:inline-block; padding:4px 10px; margin-right:8px; margin-bottom:8px; background:#f0f5f0; color:#4CAF50; border-radius:999px; font-size:12px }

.comments { margin-top: 16px }
.comments-title { font-size: 14px; color:#555; margin-bottom:8px }
.comment-list { display: flex; flex-direction: column; gap: 12px }
.comment-item { display:flex; flex-direction:column; gap:2px }
.comment-author { font-size: 13px; color:#333; font-weight:600 }
.comment-content { font-size: 14px; color:#444; line-height: 1.7 }
.comment-time { font-size: 12px; color:#999 }

.info-footer {
  flex: 0 0 auto;
  padding: 12px 16px;
  border-top: 1px solid #eee;
  display: flex;
  gap: 10px;
}
.comment-input { flex: 1; height: 40px; padding: 0 12px; border: 1px solid #ddd; border-radius: 8px; outline: none; transition: border-color 0.2s }
.comment-input:focus { border-color: #4CAF50 }
.send-btn { height: 40px; padding: 0 14px; border: none; border-radius: 999px; background: #4CAF50; color: #fff; cursor: pointer }
.send-btn:disabled { opacity: 0.6; cursor: not-allowed }

/* 滚动条美化 */
.info-body::-webkit-scrollbar { width: 6px }
.info-body::-webkit-scrollbar-thumb { background: #ddd; border-radius: 6px }
.info-body::-webkit-scrollbar-track { background: transparent }
</style>
